
#include "my_42sh.h"
#include "options_parser.h"

int                     bad_opt(char            *name)
{
  write(STDERR_FILENO, "Error: this command line is not supported by ", 45);
  write(STDERR_FILENO, name, strlen(name));
  write(STDERR_FILENO, "\n", 1);
  write(STDERR_FILENO, "Usage: 42sh [options] [files]\n", 30);

  return (1);
}

static void             free_cmd_res(s_cmd      *cmd)
{
  s_opt                 *tmp_opt = NULL;
  s_opt                 *aux = NULL;

  tmp_opt = cmd->opt;

  while (tmp_opt != NULL)
  {
    aux = tmp_opt;
    tmp_opt = tmp_opt->next;
    free(aux->name);
    free(aux->aux);
    free(aux);
  }

  if (cmd->file != NULL)
    free(cmd->file->name);

  free(cmd->file);

  free(cmd);
}

int                     main(int                argc,
                             char               **argv,
                             char               **envp)
{
  int                   *ret = NULL;
  s_cmd                 *cmd_res = NULL;

  ret = malloc(sizeof (int));
  cmd_res = option_parser(argc, argv, ret);

  if (*ret == 1)
  {
    free(ret);
    free_cmd_res(cmd_res);
    return (1);
  }

  if (exec_cmdline(cmd_res, argv, envp) != 0)
  {
    free(ret);
    free_cmd_res(cmd_res);
    return (1);
  }

  free(ret);
  free_cmd_res(cmd_res);
  return (0);
}
